package com.jinzhi.jzweb.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.CoursesDO;
import com.jinzhi.jzweb.domain.TrainingPapersDO;
import com.jinzhi.jzweb.domain.TrainingQuestionsDO;
import com.jinzhi.jzweb.service.CoursesService;
import com.jinzhi.jzweb.service.TrainingPapersService;
import com.jinzhi.jzweb.service.TrainingQuestionsService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 
 * <pre>
 * 培训试卷表
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/trainingPapers")
public class TrainingPapersController extends BaseController {
	@Autowired
	private TrainingPapersService trainingPapersService;
	@Autowired
	private UserService userService;
	@Autowired
	private CoursesService coursesService;
	@Autowired
	private TrainingQuestionsService trainingQuestionsService;

	
	@GetMapping()
	@RequiresPermissions("jzweb:trainingPapers:trainingPapers")
	String TrainingPapers(){
	    return "jzweb/trainingPapers/trainingPapers";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:trainingPapers:trainingPapers")
	public Result<Page<TrainingPapersDO>> list(HttpServletRequest req, TrainingPapersDO trainingPapersDTO){
		Wrapper<TrainingPapersDO> wrapper = new EntityWrapper<TrainingPapersDO>().orderBy("id", false);
		if (trainingPapersDTO.getState() != null){
			wrapper.eq("state",trainingPapersDTO.getState());
		}
		if (trainingPapersDTO.getType() != null){
			wrapper.eq("type",trainingPapersDTO.getType());
		}
		if (trainingPapersDTO.getName() != null){
			wrapper.like("name",trainingPapersDTO.getName());
		}
		if (trainingPapersDTO.getNumbers() != null){
			wrapper.like("numbers",trainingPapersDTO.getNumbers());
		}

		String strr = roleCourse(req,trainingPapersDTO.getCoursesName());
		if (StringUtils.isBlank(strr)) {
			wrapper.and();
			wrapper.eq("courses_id", null);
		} else if(!strr.equals("@#$%^&*!~")){
			wrapper.and();
			wrapper.in("courses_id", strr.substring(0, strr.length() - 1));
		}

        Page<TrainingPapersDO> page = trainingPapersService.selectPage(getPage(TrainingPapersDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			TrainingPapersDO obj = (TrainingPapersDO) page.getRecords().get(i);
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getUsername());
				}
			}
			if (obj.getUpdaterId() != null){
				UserDO userDO = userService.selectById(obj.getUpdaterId());
				if (userDO != null) {
					if(org.apache.commons.lang.StringUtils.isNotBlank(userDO.getName())){
						obj.setUpdaterName(userDO.getName());
					}else{
						obj.setUpdaterName(userDO.getUsername());
					}
				}
			}
			if (obj.getCoursesId() != null){
				CoursesDO coursesDO = coursesService.selectById(obj.getCoursesId());
				if (coursesDO != null) {
					obj.setCoursesName(coursesDO.getName());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:trainingPapers:add")
	String add(Model model){
		List<Map> maps;
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			Map map = new HashMap();
			map.put("orgId", this.getUser().getOrgId());
			//讲师
			if(roleName.contains("讲师") && !roleName.contains("培训机构")){
				map.put("userId",this.getUserId());
			}
			maps = coursesService.selCourseList(map);
		} else {
			maps = coursesService.selAllCourseList();
		}
		model.addAttribute("courses", maps);
	    return "jzweb/trainingPapers/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:trainingPapers:edit")
	String edit(@PathVariable("id") Long id,Model model){
		List<Map> maps;
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			Map map = new HashMap();
			map.put("orgId", this.getUser().getOrgId());
			//讲师
			if(roleName.contains("讲师") && !roleName.contains("培训机构")){
				map.put("userId",this.getUserId());
			}
			maps = coursesService.selCourseList(map);
		} else {
			maps = coursesService.selAllCourseList();
		}
		model.addAttribute("courses", maps);
		TrainingPapersDO trainingPapers = trainingPapersService.selectById(id);
		model.addAttribute("trainingPapers", trainingPapers);
	    return "jzweb/trainingPapers/edit";
	}
	
	@Log("添加培训试卷表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:trainingPapers:add")
	public Result<String> save( TrainingPapersDO trainingPapers){
		//根据课程id、类型、试卷名称判断是否重复，一个课程无论是练习或者测试都可以有多套试卷
		TrainingPapersDO trainingPapersDO = trainingPapersService
				.findOneByKv("type", trainingPapers.getType(), "courses_id", trainingPapers.getCoursesId(),"name",trainingPapers.getName());
		if (trainingPapersDO != null) {
			return Result.fail("试卷已存在，请检查");
		} else {
			TrainingPapersDO trainingPapersDO1 = trainingPapersService.findOneByKv("numbers",trainingPapers.getNumbers());
			if(trainingPapersDO1 != null){
				return Result.fail("试卷编号重复，请修改");
			}
			trainingPapers.setCreaterId(this.getUserId());
			trainingPapers.setUpdaterId(this.getUserId());
			boolean bbc = trainingPapersService.insert(trainingPapers);
			if(!bbc){
				return Result.fail();
			}
			return Result.ok();
		}
	}
	
	@Log("修改培训试卷表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:trainingPapers:edit")
	public Result<String>  update( TrainingPapersDO trainingPapers){
		//根据课程id、类型、试卷名称判断是否重复，一个课程无论是练习或者测试都可以有多套试卷
		List<TrainingPapersDO> trainingPapersDOs = trainingPapersService
				.findByKv("type", trainingPapers.getType(), "courses_id", trainingPapers.getCoursesId(),"name",trainingPapers.getName());
		if (trainingPapersDOs != null && trainingPapersDOs.size() > 0) {
			if(trainingPapersDOs.size() == 1){
				if(trainingPapersDOs.get(0).getId().equals(trainingPapers.getId())){
					List<TrainingPapersDO> trainingPapersDO1 = trainingPapersService.findByKv("numbers",trainingPapers.getNumbers());
					if(trainingPapersDO1 != null && trainingPapersDO1.size() > 0){
						if(trainingPapersDO1.size() == 1){
							if(trainingPapersDO1.get(0).getId().equals(trainingPapers.getId())){
								trainingPapers.setUpdaterId(this.getUserId());
								boolean update = trainingPapersService.updateById(trainingPapers);
								return update ? Result.ok() : Result.fail();
							}
						}
						return Result.fail("试卷编号重复，请修改");
					}else{
						trainingPapers.setUpdaterId(this.getUserId());
						boolean update = trainingPapersService.updateById(trainingPapers);
						return update ? Result.ok() : Result.fail();
					}
				}
			}
			return Result.fail("试卷已存在，请检查");
		} else {
			List<TrainingPapersDO> trainingPapersDO1 = trainingPapersService.findByKv("numbers",trainingPapers.getNumbers());
			if(trainingPapersDO1 != null && trainingPapersDO1.size() > 0){
				if(trainingPapersDO1.size() == 1){
					if(trainingPapersDO1.get(0).getId().equals(trainingPapers.getId())){
						trainingPapers.setUpdaterId(this.getUserId());
						boolean update = trainingPapersService.updateById(trainingPapers);
						return update ? Result.ok() : Result.fail();
					}
				}
				return Result.fail("试卷编号重复，请修改");
			}else{
				trainingPapers.setUpdaterId(this.getUserId());
				boolean update = trainingPapersService.updateById(trainingPapers);
				return update ? Result.ok() : Result.fail();
			}
		}
	}
	
	@Log("删除培训试卷表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:trainingPapers:remove")
	public Result<String>  remove( Long id){
		//删除考试试题
		List<TrainingQuestionsDO> trainingQuestionsDOS = trainingQuestionsService.findByKv("tpapers_id",id);
		if(trainingQuestionsDOS != null && trainingQuestionsDOS.size() > 0){
			List<Long> ids = new ArrayList<>();
			for(int j=0;j<trainingQuestionsDOS.size();j++){
				ids.add(trainingQuestionsDOS.get(j).getId());
			}
			trainingQuestionsService.deleteBatchIds(ids);
		}

		trainingPapersService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除培训试卷表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:trainingPapers:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		for(int i=0;i<ids.length;i++){
			//删除考试试题
			List<TrainingQuestionsDO> trainingQuestionsDOS = trainingQuestionsService.findByKv("tpapers_id",ids[i]);
			if(trainingQuestionsDOS != null && trainingQuestionsDOS.size() > 0){
				List<Long> idss = new ArrayList<>();
				for(int j=0;j<trainingQuestionsDOS.size();j++){
					idss.add(trainingQuestionsDOS.get(j).getId());
				}
				trainingQuestionsService.deleteBatchIds(idss);
			}
		}

		trainingPapersService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

}
